"use strict";
Object.defineProperty(exports, "__esModule", {value: true});

var mongoose = require('mongoose');
var Q = require('q');
var promise = require('promise');

var Schema = mongoose.Schema;

let schemaUser = new Schema({
        userID: {
            type: 'String',
            required: true //userID 非空
        },
        userName: {
            type: 'String',
            required: true //userName 非空
        },
        nickname: {
            type: 'String',
            required: true //nickname 非空
        },
        color: {
            type: 'String',
            default: null,
            required: false //pic 可以空
        },
        pic: {
            type: 'String',
            default: null,
            required: false //pic 可以空
        },
        updated: {
            type: Date,
            default: Date.now
        },
        hasLogined: {
            type: Boolean,
            default: false
        }
    },
    //versionKey——版本锁
    {versionKey: '__'}
);

exports.schemaUser = schemaUser;

let User = mongoose.model('Users', schemaUser);
exports.User = User;

//输出(对外暴露)一个函数 insertUser
let insertUser = function (mUser) {
    var m = new User;

    m.userID = mUser.userID;
    m.userName = mUser.userName;
    m.nickname = mUser.nickname;
    m.pic = mUser.pic;
    m.color = mUser.color;

    m.save(function (err) {
        if (err != null) {
            console.log(err);
        }
    });

};
exports.insertUser = insertUser;

//几条初始化数据,放在一个对象数组里面,测试时可以直接循环全部插入,
let initUser = function () {
    //应该使用 判断 collection 是否存在来处理,待处理
    queryByUserName('wzh').then(function () {
            //已经存在,就不再 init 了
            console.log("------已完成过,无需再次初始化------");
        }
        , function () {
            var testData = require('./testData');
            var users = testData.data;

            for (var i = 0; i < users.length; i++) {
                var insertUser123 = insertUser(users[i]);

            }

            console.log("------第一次初始化成功！------");
        }
    );

};
exports.initUser = initUser;

//查询这个用户信息
exports.queryUser = function (mUser) {
    var deferred = Q.defer();

    //直接找到一条数据,因为userName 是唯一的
    var userName = mUser.userName;

    var where = {'userName': userName}; //查询条件
    var projection = {'_id': 0};//返回所有字段,除了_id

    User.findOne(where, projection, function (err, user) {
        if (err == null) {
            deferred.resolve(user);
        }
        else {
            deferred.reject('error!No user');
        }
    });

    return deferred.promise;

};

let queryByUserName = function (userName) {
    var deferred = Q.defer();

    //直接找到一条数据,因为userName 是唯一的
    var where = {'userName': userName}; //查询条件
    var projection = {'_id': 0};//返回所有字段,除了_id

    promise = User.findOne(where, projection, function (err, user) {
        if (err == null) {
            if (user == null || user.length < 1) {
                //查询动作是成功的,但是,结果是空的,我这里给他 reject表示没有找到
                deferred.reject('error!No user');
            }
            else
                deferred.resolve(user);
        }
        else {
            console.log("222");
            deferred.reject('error!No user');
        }
    });

    return deferred.promise;

};
exports.queryByUserName = queryByUserName;

//查询用户信息
exports.queryUsers = function (page, rows) {
    var deferred = Q.defer();
    if (!dbConnected) {
        //数据库错误,直接返回
        console.log('数据库错误,直接返回 =');
        deferred.reject("<h1> 数据库错误,请检查数据库服务器是否开启</h1>");
        return deferred.promise;
    }
    ;

    //var Users = mongoose.model('Users', schemaUser);
    var where = {}; //查询条件     //找到所有数据
    var projection = {'_id': 0};//返回所有字段,除了_id

    if (page <= 0 || typeof(page) == 'undefined') page = DEFAULT_START_PAGENO;
    if (rows <= 0 || typeof(rows) == 'undefined') rows = DEFAULT_ROWS;
    if (rows > MAX_PAGE_SIZE) rows = MAX_PAGE_SIZE;

    var query = User.find(where);
    //跳过 前面页的记录
    query.skip((page - 1) * rows);
    //限制总共获取的条数
    query.limit(rows);

    query.exec(function (err, users) {
        if (err == null) {
            deferred.resolve(users);
        }
        else {
            deferred.reject('error!No user');
        }
    });

    return deferred.promise;
};
